import { CSSProperties, memo, useEffect } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Link, useParams } from 'react-router-dom';
import { Avatar, Button, message, Popconfirm, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { API_BASEURL } from '@/constants/api';
import { resAddOrCancelFollow, resFan, resFollow } from '@/services/follow';
import { userStore } from '@/store/userStore';
import { useAntdTable, useRequest } from 'ahooks';
import { useRecoilValue } from 'recoil';
import ProfileContainer from '@/components/ProfileContainer';
import { formatTime } from '@/utils/format';

const createColumns = (
  refresh: () => void,
  data?: API.FollowStruct[]
): ColumnsType<API.FollowStruct> => {
  return [
    {
      title: <div className={'font-bold'}>用户名称</div>,
      align: 'center',
      render: (_, fans) => (
        <div className={'flex-justify-items-center'}>
          <Avatar src={API_BASEURL + '/' + fans?.fans?.avatar} />
          <Link to={`/user_page/` + fans?.fans?.id} className={'ml-2'}>
            {fans.fans?.name}
          </Link>
        </div>
      ),
    },
    {
      title: <div className={'font-bold'}>关注时间</div>,
      dataIndex: 'created_at',
      align: 'center',
      render: (create_at) => <div>{formatTime(create_at)}</div>,
    },
  ];
};

const FansPage: FC<
  PropsWithChildren<{
    style?: CSSProperties;
    showTitle?: boolean;
    refreshCount?: number;
  }>
> = ({ style, showTitle = true, refreshCount }) => {
  const user = useRecoilValue(userStore);
  const params = useParams();
  const id = Number(params.id) || user.id;
  const { data, refresh: refreshFollow } = useRequest(resFollow, {
    defaultParams: [id],
  });
  const { tableProps, pagination } = useAntdTable(
    ({ pageSize, current }) => {
      return resFan(id, {
        pageSize,
        current,
      });
    },
    { cacheKey: 'useFansCache' }
  );

  const refresh = () => {
    pagination.changeCurrent(pagination.current);
    refreshFollow();
  };

  useEffect(() => {
    refresh();
  }, [refreshCount]);

  const columns = createColumns(refresh, data?.list);
  return showTitle ? (
    <ProfileContainer title={'我的关注'} style={style}>
      <Table columns={columns} rowKey="id" {...tableProps} />
    </ProfileContainer>
  ) : (
    <Table columns={columns} rowKey="id" {...tableProps} />
  );
};

export default memo(FansPage);
